import 'package:flutter_soundmagus/page/inout/summing_controller.dart';
import 'package:flutter_soundmagus/util/bridge.dart';
import 'package:flutter_soundmagus/widget/alert/alert.dart';
import 'package:flutter_soundmagus/widget/eq/eq.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';

class SaveItem {
  String name;
  String value;
  DateTime dateTime;
  bool usePwd;
  SaveItem(
      {required this.name,
      required this.value,
      required this.dateTime,
      this.usePwd = false});
}

class SaveController extends GetxController {
  final box = Hive.box('settings');
  static const boxDateKey = 'settings_date';
  static const boxPwdKey = 'settings_pwd';

  ///默认密码
  static const kPwdDefault = '666666';

  SaveController() {
    ///读取密码
    lastPwd();
  }

  ///密码
  String pwd = kPwdDefault;
  void create({required String name, bool usePwd = false}) async {
    try {
      final value = DataMng().getSaveString();
      box.put(name, value);

      final boxDate = await Hive.openBox(boxDateKey);
      boxDate.put(name, DateTime.now());

      boxDate.put(name + 'pwd', usePwd);
      Fluttertoast.showToast(msg: 'setting create sucess');
    } catch (e) {
      Fluttertoast.showToast(msg: 'setting create error');
    }
  }

  void delete({required String name}) {
    box.delete(name);
  }

  Future<List<SaveItem>> getAll() async {
    var rs = <SaveItem>[];
    final boxDate = await Hive.openBox(boxDateKey);
    for (var key in box.keys) {
      try {
        var v = box.get(key);
        var date = boxDate.get(key);
        var usePwd = boxDate.get(key + 'pwd');
        rs.add(SaveItem(
            name: key,
            dateTime: date,
            value: v,
            usePwd: usePwd == null ? false : usePwd));
      } catch (e) {
        print(e);
      }
    }
    return rs;
  }

  List<dynamic>? load({required String name, bool coverthis = false}) {
    final str = box.get(name);
    return DataMng().loadFromString(str, coverthis: coverthis);
  }

  savePwd(String pwd) async {
    final box = await Hive.openBox(boxPwdKey);
    box.put('pwd', pwd);
  }

  Future<String?> lastPwd() async {
    final box = await Hive.openBox(boxPwdKey);
    pwd = box.get('pwd', defaultValue: kPwdDefault);
    return pwd;
  }

  ///重置密码
  void resetPwd() async {
    pwd = kPwdDefault;
    await savePwd(kPwdDefault);
  }

  ///修改密码
  void changePwd(String newPwd) {
    pwd = newPwd;
    savePwd(newPwd);
  }

  void onBasicPress() {
    Get.dialog(AlertSettingNew(onPressed: (name) {
      create(name: name);
      Get.back();
    }));
  }

  void onAdvancedPress() {
    if (pwd == kPwdDefault) {
      //密码为空时，先设置密码
      Get.dialog(AlertSetPwd(
        onPressed: (pwd) {
          this.pwd = pwd;
          savePwd(pwd);
          Get.back();
          _doCreateUserPwd();
        },
      ));
      return;
    }
    //输入密码
    Get.dialog(AlertEnterPwd(
      onPressed: (input) {
        if (input != pwd) {
          Fluttertoast.showToast(msg: 'Password error');
          return;
        }
        _doCreateUserPwd();
      },
    ));
  }

  _doCreateUserPwd() {
    Future.delayed(Duration(milliseconds: 200), () {
      Get.dialog(AlertSettingNew(
        onPressed: (name) {
          create(name: name, usePwd: true);
          Get.back();
        },
      ));
    });
  }

  void onItemPress(SaveItem item) {
    if (item.usePwd) {
      Get.dialog(AlertEnterPwd(
        onPressed: (input) {
          if (input != pwd) {
            Fluttertoast.showToast(msg: 'Password error');
            return;
          }
          load(name: item.name, coverthis: true);
          _doLoadData();
        },
      ));
    } else {
      load(name: item.name, coverthis: true);
      _doLoadData();
    }
  }

  ///邮件分享
  void onShare(SaveItem item) {
    var str = box.get(item.name);
    str = DataMng().shareCmdString(str);
    Bridge.share(str);
  }

  ///下发数据
  _doLoadData() {
    Get.back();
    showLoading(duration: Duration(seconds: 5));
    MsgParser.done(sendData: true);
  }

  void resetDsp() {
    //重置数据
    DataMng.reset();
    //刷新UI
    MsgParser.done(sendData: false);
    //重置指令
    Msg.msgResetDsp();
  }
}
